package com.dayuanit.dy17.atm.service.impl;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy17.atm.dto.FlowDTO;
import com.dayuanit.dy17.atm.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.params.SetParams;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class RedisServiceImpl implements IRedisService {

    @Autowired(required = false)
    private JedisPool jedisPool;

    @Override
    public boolean saveResetPwdEmail(String email) {
        try (Jedis jedis = jedisPool.getResource()) {
            SetParams params = SetParams.setParams().nx().ex(30);
            String result = jedis.set("atm:email:" + email, "", params);
            return "ok".equalsIgnoreCase(result);
        }
    }

    @Override
    public void saveTop10Flows(long userId, List<FlowDTO> flows) {
        String key = "atm:flow:" + userId;
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(key, JSON.toJSONString(flows), SetParams.setParams().ex(10));
        }
    }

    @Override
    public List<FlowDTO> listTop10Flows(long userId) {
        String key = "atm:flow:" + userId;
        try (Jedis jedis = jedisPool.getResource()) {
            String value = jedis.get(key);
            if (null == value){
                return Collections.emptyList();
            }
            return JSON.parseArray(value, FlowDTO.class);
        }
    }

    @Override
    public void expireKey(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.expire(key, 0);
        }
    }
}
